package controller;

import gui.OptionPane;

import java.rmi.RemoteException;

import model.MessageInterface;
import model.UserInterface;
import toolkit.Debug;

public class NewMessage extends Controller
{
	private String to, subject, contents;
	
	public NewMessage()
	{
		setView(new view.NewMessage(this));
	}

	public NewMessage(UserInterface to)
	{
		String toUsername = to.getUsername();
		
		setTo(toUsername);
		
		setView(new view.NewMessage(this, toUsername));
	}
	
	public void setTo(String to)
	{
		this.to = to;
	}
	
	public void setSubject(String subject)
	{
		this.subject = subject;
	}
	
	public void setContents(String contents)
	{
		this.contents = contents;
	}
	
	public void send()
	{
		if (to.isEmpty())
		{
			OptionPane.showError("Empty to username", "Please fill in a username to send to.");
		}
		else if (!Debug.isEnabled() && to.equalsIgnoreCase(user.getUsername()))
		{
			OptionPane.showError("Invalid to username", "You cannot send messages to your own.");
		}
		else if (contents.isEmpty())
		{
			OptionPane.showError("Empty message", "Please fill in a message.");
		}
		else
		{
			try
			{
				UserInterface recipient = messageRemote.getRecipient(to);
				
				if (recipient == null)
				{
					OptionPane.showError("Invalid to username", "Please fill in a valid username to send to.");
				}
				else
				{
					MessageInterface message = messageRemote.newMessage(user);
					
					message.setTo(recipient);
					message.setSubject(subject);
					message.setContents(contents);
					
					messageRemote.storeMessage(message);
					
					forward(new controller.Inbox());
				}
			}
			catch (RemoteException e)
			{
				Debug.log(e);
				
				OptionPane.showError("Error", "Something went wrong when trying to send the message.");
			}
		}
	}
	
	public void cancel()
	{
		goBack();
	}
}
